<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
    <title>设备联动</title>
    <link rel="stylesheet" href="../css/header.css">
    <link rel="stylesheet" href="../css/layout.css">
    <script type="text/javascript" src="../script/api.js"></script>
    <script type="text/javascript" src="../script/mqttws31.js"></script>
    <script type="text/javascript" src="../script/jquery-2.1.3.js"></script>
    <script type="text/javascript" src="../script/mico_speech.js"></script>
</head>
<body>
    <div class="wrapper wuhuakongzhiqi"> 
        <!-- header -->
        <header id="header" class="header">
            <div class="head">
                <a class="left" onclick="checkpage()" id="backleft"></a>
                <span class="center" id="device_name">图片上传下载</span>
                <a id="backright"></a>
            </div>
        </header>
        <!-- content -->
        <div class="content">
            <div class="block imagedisp clearfix">
                <img id="imgid" src="../image/login-micokit.svg">
                <div class="imgdisp">##图片</div>
            </div>
            <div class="block imageopra clearfix">
                <div class="col_50">
                    <div class="openimg">打开</div>
                </div>
                <div class="col_50">
                    <div class="uploadimg">上传</div>
                </div>
            </div>
            <div class="block oprainfo clearfix">
                <textarea></textarea>
            </div>
            <br/>
            <div id="device_id"></div>
            <div id="debug"></div>
        </div>
    </div>
</body>
    <script>
        var device_id;
        var micoMqtt = null;
        //听我指令
        var listenme = 0;
        apiready = function() {
            //alert(api.systemVersion.substring(0,3));
            if (parseFloat(api.systemVersion.substring(0,3)) >= 4.4) {
                $(".header").css("padding-top", "35px");
                $(".content").css("height", document.body.clientHeight - 76);
            } else {
                $(".header").css("padding-top", "15px");
                $(".content").css("height", document.body.clientHeight - 56);
            }
            device_id = api.pageParam.deviceid;
            document.getElementById('device_name').innerHTML = api.pageParam.devicename;
            // 如果设备ID不为空，则执行连接MQTT的操作
            if (device_id !== null) {
                ez_connect(device_id);
            }
            if (api.systemType != 'ios') {
                api.addEventListener({
                    name : "keyback"
                }, function(ret, err) {
                    checkpage();
                });
            } else {
                // $(".header").css("padding-top", "30px");
                // $(".left").css("top", "32px");
            }
        };
        // 连接MQTT服务
        function ez_connect(device_id) {
            document.getElementById('device_id').innerHTML = "设备ID：" + device_id;
            //首先引用MiCOmqtt
            micoMqtt = api.require("micoMqtt2");
            var host = "api.easylink.io";
            var username = "";
            var password = "";
            //clientID，需要按照此标准来定义：v1-app-[MAC]  版本号-app-手机MAC(12位)
            var clientID = "v1-app-" + parseInt(Math.random() * (1000000000000), 12);
            var topic = device_id + '/out/#';
            micoMqtt.startMqtt({
                micoMqtt : micoMqtt,
                host : host,
                username : username,
                password : password,
                clientID : clientID,
                topic : topic
            }, function(ret, err) {
                if (ret.status) {
                    console.log("连接成功");
                    recvmsg();
                } else {
                    console.log("连接失败");
                }
            });
        }

        var recvimgdata;    //接收到的图片数据

        var sendimgdata;     //发送的图片数据
        var openimgdata;    //打开的图片数据
        var openimgname = "test.jpg";    //打开的图片名

        var send_file_name;
        var send_group_num;
        var send_file_mem_len;
        var send_file_mem_info;
        var sendimgstr;     //发送的图片的字符串数据

        //var package_num = 0;    //5数据包计数

        //var recv_msg_id;
        var recv_file_name;
        var recv_group_num;
        // var recv_member_total;
        // var recv_member_num;
        //var recv_ELF;
        var recv_file_mem_len;
        var recv_file_mem_info;

        ///打开图库，选择图片得到base64编码后的图片字符串
        function openimg(){
            api.getPicture({
                sourceType: 'library',
                encodingType: 'jpg',
                mediaValue: 'pic',
                destinationType: 'base64',
                allowEdit: true,
                quality: 50,
                targetWidth:100,
                targetHeight:100,
                saveToPhotoAlbum: false
            }, function(ret, err) {
                if (ret) {
                        openimgdata = ret.base64Data;
                        //openimgname = ret.data;     //文件路径
                        //api.alert("ret.data: "+{msg:ret.data});
                    } else{
                        api.alert("error msg: " + {msg:err.msg});
                    }
            });
        }
        
        function sendimg(){
            if(openimgdata != ""){
                sendimgdata = openimgdata.substring(22,openimgdata.length);
                send_file_name = openimgname.substring(0,openimgname.length);   //修改下文件名
                send_group_num = 0;     //初始化包计数
                send_file_mem_len = 384;    //初始化子包大小
                send_file_mem_info = "";    //初始化包信息
                sendimgstr = CharToHex(base64decode(sendimgdata));  //总包信息
                //alert("imgStr: " + imgStr);
                
                sendImgSubBegin(send_file_name,sendimgstr.length/2); //发包头，2个字符表示一个字节
                openimgdata = "";
            }else{
                alert("上传图片不可为空，请重新打开文件。");
            }
        }

        function sendImgSubBegin(file_name, file_len){
            var topic = device_id + '/in';
            var command;
            var command = '{"msg_id":11, "file_name":"'+file_name+'", "file_len":'+file_len+'}';
            publishcmd(topic, command);
        }

        function sendImgSubBody(file_name, group_num, file_mem_len, file_mem_info){
            var topic = device_id + '/in';
            var command;
            var command = '{"msg_id":13, "file_name":"' + file_name + '", "group_num":'+ group_num + '", "file_mem_len":'+ file_mem_len + '", "file_mem_info":'+ file_mem_info +'}';
            publishcmd(topic, command);
        }

        function sendImgSubEnd(file_name){
            var topic = device_id + '/in';
            var command;
            var command = '{"msg_id":15, "file_name":"' + file_name + '}';
            publishcmd(topic, command);
        }

        $(".openimg").click(function(){
            //alert("openimg");
            openimg();
            document.getElementById("imgid").src = openimgdata;
            document.getElementById("imgid").src = openimgdata;
            // $(".imagedisp>img").src = sendimgdata;//"data:image/jpg;base64," + 
        });

        $(".uploadimg").click(function(){
            sendimg();
        });

        function startack(file_name, file_len){
            var topic = device_id + '/in';
            var command;
            var command = '{"msg_id":2, "file_name":"'+file_name+'", "file_len":'+file_len+'}';
            publishcmd(topic, command);
        }

        function filerecvcheck(file_name, group_num, file_mem_len, file_mem_info){
            // alert("check: " + file_name +"-"+ recv_file_name + " " + group_num + "-" + recv_group_num + " " + file_mem_len + "-" + file_mem_info.length);
            if((file_name == recv_file_name) && file_mem_info.length/2 == file_mem_len){
                return true;
            }else{
                return false;
            }
        }

        function filerecvack(re_send, file_name, group_num){
            var topic = device_id + '/in';
            var command;
            var command = '{"msg_id":4'+', "re_send":'+re_send+', "file_name":"'+file_name+'", "group_num":'+group_num+'}';
            publishcmd(topic, command);
        }

        function recvimg(file_mem_info){
            recvimgdata += file_mem_info;
        }

        function endack(file_name){
            var topic = device_id + '/in';
            var command;
            var command = '{"msg_id":6, "file_name":"'+file_name+'"}';
            publishcmd(topic, command);
        }

        //显示收到的图片
        function dispimg(){
            var hextochar = HexToChar(recvimgdata);
            var base64encodeimg = base64encode(hextochar);
            
            document.getElementById("imgid").src = "data:image/jpg;base64," + base64encodeimg;
            document.getElementById("imgid").src = "data:image/jpg;base64," + base64encodeimg;

            alert("图片接收成功！");
        }

        var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        var base64DecodeChars = new Array(
            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
            52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
            -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
            15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
            -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
            41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);

        function base64encode(str) {
            var out, i, len;
            var c1, c2, c3;

            len = str.length;
            i = 0;
            out = "";
            while(i < len) {
            c1 = str.charCodeAt(i++) & 0xff;
            if(i == len)
            {
                out += base64EncodeChars.charAt(c1 >> 2);
                out += base64EncodeChars.charAt((c1 & 0x3) << 4);
                out += "==";
                break;
            }
            c2 = str.charCodeAt(i++);
            if(i == len)
            {
                out += base64EncodeChars.charAt(c1 >> 2);
                out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
                out += base64EncodeChars.charAt((c2 & 0xF) << 2);
                out += "=";
                break;
            }
            c3 = str.charCodeAt(i++);
            out += base64EncodeChars.charAt(c1 >> 2);
            out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
            out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6));
            out += base64EncodeChars.charAt(c3 & 0x3F);
            }
            return out;
        }

        function base64decode(str) {
            var c1, c2, c3, c4;
            var i, len, out;

            len = str.length;
            i = 0;
            out = "";
            while(i < len) {
            /* c1 */
            do {
                c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
            } while(i < len && c1 == -1);
            if(c1 == -1)
                break;

            /* c2 */
            do {
                c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
            } while(i < len && c2 == -1);
            if(c2 == -1)
                break;

            out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));

            /* c3 */
            do {
                c3 = str.charCodeAt(i++) & 0xff;
                if(c3 == 61)
                return out;
                c3 = base64DecodeChars[c3];
            } while(i < len && c3 == -1);
            if(c3 == -1)
                break;

            out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));

            /* c4 */
            do {
                c4 = str.charCodeAt(i++) & 0xff;
                if(c4 == 61)
                return out;
                c4 = base64DecodeChars[c4];
            } while(i < len && c4 == -1);
            if(c4 == -1)
                break;
            out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
            }
            return out;
        }

        function CharToHex(str) {
            var out, i, len, c, h;
            out = "";
            len = str.length;
            i = 0;
            while(i < len) {
                c = str.charCodeAt(i++);    //返回指定位置的字符的 Unicode 编码
                h = c.toString(16);         
                if(h.length < 2)
                    h = "0" + h;
                out += h;
            }
            return out;
        }

        function HexToChar(str) {
            var out, i, len, c, h;
            out = "";
            len = str.length;
            i = 0;
            while(i < len){
                c = parseInt((str[i]+str[i+1]),16);
                i += 2;
                h = String.fromCharCode(c);
                out += h;
            }
            return out;
        }

        // 接收数据
        function recvmsg() {
            var msgindex = 1;
            var msgjson;
            micoMqtt.recvMqttMsg(function(ret, err) {
                //              alert(JSON.stringify(ret));
                if (ret) {
                    if (msgindex > 12) {
                        msgindex = 1;
                        document.getElementById('debug').innerHTML = "";
                    }
                    msgindex++;
                    msgjson = ret.subs;

                    //1.开始信号
                    //2.接收数据包并处理
                    //3.结束信号，显示处理

                    var msg_id = msgjson.msg_id;
                    var file_name = msgjson.file_name;
                    var group_num = msgjson.group_num;
                    // var member_total = msgjson.member_total;
                    // var member_num = msgjson.member_num;
                    //var ELF = msgjson.ELF;
                    var file_len = msgjson.file_len;
                    var file_mem_len = msgjson.file_mem_len;
                    var file_mem_info = msgjson.file_mem_info;

                    var re_send = msgjson.re_send;

                    if ("undefined" != typeof (msg_id)) {
                        switch(msg_id){
                            case 1: 
                                recvimgdata = ""; 
                                recv_group_num = -1; //包计数
                                startack(file_name, file_len); 

                                recv_file_name = file_name;
                                //alert("got it at send 2");

                                $(".oprainfo>textarea").text("msg_id: "+msg_id); 
                                break;
                            case 12:    //收到包头,开始发送第0包数据
                                sendImgSubBody(send_file_name, send_group_num, send_file_mem_len, sendimgstr.substring(send_file_mem_len*send_group_num*2,send_file_mem_len*(send_group_num+1)*2));


                                // while(send_group_num*send_file_mem_len < sendimgstr.length){
                                //     sendImgSubBody(send_file_name, send_group_num, send_file_mem_len, sendimgstr.substring(send_file_mem_len*send_group_num,send_file_mem_len*(send_group_num+1)));
                                //     i++;
                                //     send_group_num++;
                                //     sleep(200);    //延时200ms
                                // }
                                break;
                            case 14:
                                if(re_send || file_name!=send_file_name || group_num!=send_group_num){    //重发
                                    sendImgSubBody(send_file_name, send_group_num, send_file_mem_len, sendimgstr.substring(send_file_mem_len*send_group_num*2,send_file_mem_len*(send_group_num+1)*2));
                                }else{
                                    send_group_num++;
                                    if(send_file_mem_len*send_group_num < sendimgstr.length){
                                        sendImgSubBody(send_file_name, send_group_num, send_file_mem_len, sendimgstr.substring(send_file_mem_len*send_group_num*2,send_file_mem_len*(send_group_num+1)*2));
                                    }else{
                                        sendImgSubEnd(send_file_name);
                                    }
                                }
                                break;
                            case 16:
                                if(file_name==send_file_name){
                                    alert("图像发送成功！");
                                }else{
                                    alert("图像发送失败！");
                                }
                                break;
                            case 3: 
                                if(filerecvcheck(file_name, group_num, file_mem_len, file_mem_info)){
                                    if(group_num == recv_group_num+1){
                                        recvimg(file_mem_info);    //保存图片数据
                                        recv_group_num = group_num;   //包计数加1
                                    }
                                    filerecvack(false,file_name, group_num);  //正确。回复ack
                                }else{
                                    filerecvack(true,file_name, group_num);   //校验错，重发
                                }
                                $(".oprainfo>textarea").text("msg_id: "+msg_id);
                                break;
                            case 5: endack(file_name); dispimg(); $(".oprainfo>textarea").text("msg_id: "+msg_id); break;
                            default: break;
                        }
                    }
                } else {
                    api.alert({
                        msg : err.msg
                    });
                }
            });
        }

        //发送指令
        function publishcmd(topic, command) {
            micoMqtt.publish({
                topic : topic,
                command : command
            }, function(ret, err) {
            });
        }


        // 日志打印在页面的部分
        var i = 0;
        console.log = ( function(old_funct, div_log) {
                return function(text) {
                    old_funct(text);
                    var p = '';
                    if (i % 2 == 0)
                        p = '<p>';
                    else
                        p = '<p class=\'gray\'>';
                    if ( typeof text === "object")
                        div_log.innerHTML += p + JSON.stringify(text) + '</p>';
                    else
                        div_log.innerHTML += p + text + '</p>';
                    div_log.scrollTop = div_log.scrollHeight;
                    i += 1;
                };
            }(console.log.bind(console), document.getElementById("debug")));
        console.error = console.debug = console.info = console.log;
        //      返回上一页
        function checkpage() {
            //关闭mqtt，关闭的时候需要同事关闭消息接收和MQTT连接
            micoMqtt.stopRecvMqttMsg(function(ret, err) {
            });
            micoMqtt.stopMqtt(function(ret, err) {
            });
            window.location.href = "./devlist.html";
        };
    </script>
</html>
